const fs = require("fs");

var fileReadStream = fs.createReadStream("./logs/greeting.log");
var fileWriteStream = fs.createWriteStream("./logs/greeting2.log");

// /* IO流写法1 */
// fileReadStream.pipe(fileWriteStream);

/* IO流写法2 */
const { pipeline } = require("stream");
pipeline(fileReadStream, fileWriteStream, (err) => {
    if (err) {
        console.error("An error occurred:", err);

        // 退出当前进程（程序自杀）
        // process=当前进程
        // process.exitCode = 1;
        process.exit(1);
    } else {
        console.log("文件写出成功！");
    }
});

/* 文件流IO事件监听 */
// fileReadStream.once("data", (chunk) => {
//     console.log("once", chunk.toString());
// });

var count = 0;
fileReadStream.on("data", (chunk) => {
    console.log(
        `${++count} 接收到：${chunk.length}字节的数据`,
        chunk,
        chunk.toString()
    );
});

fileReadStream.on("end", () => {
    console.log("--- 读取结束 ---");
});

fileReadStream.on("error", (error) => {
    console.log("error=", error);
});
